<template lang="pug">
  div.letter-indexer
    touch-bar(
      @picked="onLetterTouch",
      :list="classifiedMapKeys")
    div.letter-indexer__content-box(ref="content-box")
      slot(name="content-top")
      div.letter-indexer__content
        template(v-for="key in classifiedMapKeys")
          header-bar(:ref="key") {{ key }}
          div.letter-indexer__content-list
            template(v-for="item in classifiedMap[key]")
              slot(:item="item")
                content-item(@click.native="onContentClick(item)")
                    | {{ item[showName] }}
                    span(v-if="descriptionName").content-item__description {{ item[descriptionName] }}
</template>

<script lang="ts">
import { Vue, Component, Prop, Emit } from 'vue-property-decorator'
import TouchBar from '@/components/touch-bar.vue'
import HeaderBar from './header-bar.vue'
import ContentItem from './content-item.vue'
import { eachWrap } from '@/utils/handle'

@Component({
  components: {
    TouchBar,
    HeaderBar,
    ContentItem
  }
})
export default class LetterIndexer extends Vue {
  @Prop() public list!: any[]
  @Prop() public keyName!: string
  @Prop() public showName!: string
  @Prop() public itemKeyName!: string
  @Prop() public descriptionName!: string

  get classifiedMapKeys() {
    const keys = Object.keys(this.classifiedMap)
    const initials = keys.filter((key: string) => /[a-zA-Z]/.test(key)).sort()
    const others = keys.filter((key: string) => !/[a-zA-Z]/.test(key)).sort()
    return [...others, ...initials]
  }

  // get wrapedList() {
  //   const { keyName } = this;
  //   return eachWrap(this.list, { keyName });
  // }

  get classifiedMap() {
    const { list, keyName } = this
    return list.reduce((prev: any, cur, index) => {
      const matchInitialList = prev[cur[keyName]]
      if (!matchInitialList) {
        prev[cur[keyName]] = []
      }

      prev[cur[keyName]].push(cur)
      return prev
    }, {})
  }

  private onLetterTouch(item: string) {
    const $el = (this.$refs[item] as Vue[])[0].$el
    const offsetTop = $el.offsetTop
    const $contentEl = this.$refs['content-box'] as any
    // FIXME: opmitize
    $contentEl.scrollTop = offsetTop - $contentEl.offsetTop
  }

  @Emit('item-click')
  private onContentClick(item: any) {}
}
</script>


<style lang="stylus" scoped>
.letter-indexer
  height 100%
  &__content-box
    width 100%
    height 100%
    overflow scroll
.content-item__description
  margin-left 10px
  font-size 14px
  color #999
</style>
